<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>15_异步处理-生成器代码的优化</title>
</head>
<body>

  <script>
    // 封装请求的方法: url -> promise(result)
    function requestData(url) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(url)
        }, 2000)
      })
    }

    // 生成器函数
    function* getData() {
      const res1 = yield requestData('http://www.baidu.com')
      console.log(res1)
      
      const res2 = yield requestData(res1 + '/data1')
      console.log(res2)

      const res3 = yield requestData(res2 + '/data2')

      const res4 = yield requestData(res3 + '/data3')
      console.log(res4)
    }

    // 执行生成器函数: 返回一个迭代器
    function execGenFn(genFn) {
      // 1. 获取generator函数
      const generator = genFn()
      // 2. 定义一个递归函数
      function exec(res) {
        // 3. 执行迭代器
        const result = generator.next(res)
        // 4. 判断是否执行完毕
        if (result.done) return result.value
        // 5. 没有执行完毕, 继续执行
        result.value.then(res => {
          exec(res)
        })
      }
      exec()
    }

    execGenFn(getData)


  </script>
  
</body>
</html>